package com.project.common.domain;

import lombok.Data;
import org.springframework.data.domain.Page;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * 分页响应封装
 *
 */
@Data
public class Pages<D> extends BaseDoConvert {
    private Integer totalPages;
    private Integer currPage;
    private Long totalElements;
    private List<D> content = new ArrayList<>();

    public static synchronized Pages of(Page page) {
        return new Pages(page);
    }

    public Pages() {
        this.currPage = 0;
        this.totalPages = 0;
        this.totalElements = 0L;
    }

    public Pages(Page page) {
        this.totalPages = page.getTotalPages();
        this.totalElements = page.getTotalElements();
        this.currPage = page.getNumber() + 1;
        if (page.hasContent()) {
            for (Object po : page.getContent()) {
                try {
                    D d = (D) po.getClass().getDeclaredConstructor().newInstance();
                    map(po, d);
                    this.content.add(d);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Pages empty() {
        return new Pages();
    }
}
